package com.nhjf.common.util.tools;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * COOKIE工具类
 * 
 * @author Administrator
 * 
 */
public class CookieTool {
    
	
	private static final CookieTool  cookieTool=new CookieTool();
	
	private CookieTool(){};
	
	public static CookieTool getInstance(){
	       return 	cookieTool;
	}

   /**
	 * 
	 * @param cookieName  
	 * @param cookieValue
	 * @param time  如：60 * 60 * 24 * 7 * 2
	 * @param response
	 */
	public  void saveCookie(HttpServletResponse response,
			String cookieName, String cookieValue, int time) {
		try {
			cookieValue = URLEncoder.encode(cookieValue, "utf-8");
             // 开始保存Cookie
			Cookie cookie = new Cookie(cookieName, cookieValue);
			 // 存两个星期(这个值应该大于或等于validTime)
			cookie.setMaxAge(time);
			 // cookie有效路径是网站根目录
			cookie.setPath("/");
			 // 向客户端写入
			response.addCookie(cookie);

		} catch (UnsupportedEncodingException e) {
			LogMessage.logwrite(this.getClass(), e.getMessage());
		}
	}

	public  String readCookie(HttpServletRequest request,
			String cookieName) {
		// 根据cookieName取cookieValue
		String cookieValue = null;
		try {
			Cookie cookies[] = request.getCookies();
			if (cookies != null) {
				for (int i = 0; i < cookies.length; i++) {
					if (cookies[i].getName().equals(cookieName)) {
						cookieValue = cookies[i].getValue();
						break;
					}
				}
			}
			cookieValue = new String(URLDecoder.decode(cookieValue, "utf-8"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return cookieValue;
	}
	
	
	// 用户注销时,清除Cookie,在需要时可随时调用------------------------------------------------------------
	public  void clearCookie(HttpServletResponse response,String cookieName) {
		Cookie cookie = new Cookie("cookieName", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

}
